import { http } from "@/utils/http";
// import { getToken } from "@/utils/auth";
import { getToken175, getToken43 } from "@/utils/token";

type Result = {
  message: string;
  data: any;
  code: number;
};

// 为task API添加Authorization头的辅助函数
const taskRequest = <T>(method: string, url: string, data?: object) => {
  const token = getToken175(); // 每次调用都获取最新的token
  return http.request<T>(method as any, url, {
    data,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

const remoteRequest = <T>(method: string, url: string, data?: object) => {
  const remoteToken = getToken43(); // 每次调用都获取最新的token
  return http.request<T>(method as any, url, {
    data,
    headers: {
      Authorization: remoteToken ? `Bearer ${remoteToken}` : undefined,
    },
  });
};

export const getDepartmentIp = (data?: object) => {
  return taskRequest<Result>("post", "/api/api/asset/department_ip", data);
};

// IP段权重相关接口
export const getIpSegmentWeights = (data?: {
  department?: string;
  page?: number;
  per_page?: number;
}) => {
  return taskRequest<Result>("post", "/api/asset/ip_segment_weights", data);
};

export const calculateIpSegmentWeights = () => {
  return taskRequest<Result>(
    "post",
    "/api/asset/calculate_ip_segment_weights",
    {}
  );
};

export const getDepartmentIpDistribution = () => {
  return taskRequest<Result>(
    "post",
    "/api/asset/department_ip_distribution",
    {}
  );
};

// 资产任务列表接口
export const getAssetTasks = (params?: {
  page?: number;
  page_size?: number;
  keyword?: string;
  date_range?: number; // 7 | 30 | 90 | 0(全部)
  has_suspected?: boolean | null; // null(全部) | true(有疑似) | false(无疑似)
  sort_by?: "scan_time" | "task" | "suspected_count";
  sort_order?: "asc" | "desc";
}) => {
  const token = getToken175();
  return http.request<Result>("get", "/api/asset-tasks", {
    params,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 获取任务详情
export const getAssetTaskDetail = (task: string) => {
  const token = getToken175();
  return http.request<Result>("get", `/api/asset-tasks/${task}`, {
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 导出任务报告
export const exportAssetTaskReport = (
  task: string,
  format: string = "excel"
) => {
  const token = getToken175();
  return http.request<Blob>("get", `/api/asset-tasks/${task}/export`, {
    params: { format },
    responseType: "blob",
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 部门关键词管理相关接口（weight 组件使用）
export const getKeywords = (params?: {
  page?: number;
  page_size?: number;
  department?: string;
  keyword?: string;
  sort_by?: "department" | "weight" | "hit_count" | "created_time";
  sort_order?: "asc" | "desc";
}) => {
  const token = getToken175();
  return http.request<Result>("get", "/api/keywords", {
    params,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 新增关键词
export const createKeyword = (data: {
  department: string;
  keyword: string;
  weight: number;
  remark?: string;
}) => {
  return taskRequest<Result>("post", "/api/keywords", data);
};

// 更新关键词
export const updateKeyword = (
  id: number,
  data: {
    weight?: number;
    remark?: string;
  }
) => {
  return taskRequest<Result>("put", `/api/keywords/${id}`, data);
};

// 获取关键词建议（智能检测）
export const getKeywordSuggestion = (keyword: string) => {
  const token = getToken175();
  return http.request<Result>("get", "/api/keywords", {
    params: { keyword },
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 删除关键词
export const deleteKeyword = (id: number) => {
  return taskRequest<Result>("delete", `/api/keywords/${id}`);
};

// 批量导入关键词
export const batchImportKeywords = (formData: FormData) => {
  const token = getToken175();
  return http.request<Result>("post", "/api/keywords/batch-import", {
    data: formData,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
      "Content-Type": "multipart/form-data",
    },
  });
};

// 批量导出关键词
export const exportKeywords = (params?: {
  department?: string;
  keyword?: string;
}) => {
  const token = getToken175();
  return http.request<Blob>("get", "/api/keywords/export", {
    params,
    responseType: "blob",
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 下载关键词导入模板
export const downloadKeywordTemplate = () => {
  const token = getToken175();
  return http.request<Blob>("get", "/api/keywords/template", {
    responseType: "blob",
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 查询疑似资产列表
export const querySuspectedAssets = (data?: {
  page?: number;
  page_size?: number;
  task?: string;
  status?: "pending" | "inferred" | "confirmed" | "rejected" | "whitelisted";
  ip_version?: 4 | 6;
  confidence_min?: number;
  confidence_max?: number;
  is_high_risk?: boolean | null;
  keyword?: string;
  sort_by?: "confidence" | "created_time" | "last_detected";
  sort_order?: "asc" | "desc";
}) => {
  const token = getToken175();
  return http.request<Result>("post", "/api/suspected-assets/query", {
    data,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 批量推理
export const batchInferSuspectedAssets = (data: {
  ids: number[];
  force?: boolean;
}) => {
  const token = getToken175();
  return http.request<Result>("post", "/api/suspected-assets/batch-infer", {
    data,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 确认推理结果
export const confirmSuspectedAsset = (
  id: number,
  data?: {
    confirmed_department?: string;
    comment?: string;
  }
) => {
  const token = getToken175();
  return http.request<Result>("post", `/api/suspected-assets/${id}/confirm`, {
    data,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 拒绝推理结果
export const rejectSuspectedAsset = (
  id: number,
  data: {
    correct_department: string;
    reject_reason: string;
  }
) => {
  const token = getToken175();
  return http.request<Result>("post", `/api/suspected-assets/${id}/reject`, {
    data,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 获取推理详情
export const getInferenceDetail = (assetId: number) => {
  const token = getToken175();
  return http.request<Result>(
    "get",
    `/api/suspected-assets/${assetId}/inference-detail`,
    {
      headers: {
        Authorization: token ? `Bearer ${token}` : undefined,
      },
    }
  );
};

// 导出推理详情
export const exportInferenceDetail = (
  assetId: number,
  data?: {
    format?: "pdf" | "excel";
    include_sections?: string[];
  }
) => {
  const token = getToken175();
  return http.request<Blob>(
    "post",
    `/api/suspected-assets/${assetId}/export-detail`,
    {
      data,
      responseType: "blob",
      headers: {
        Authorization: token ? `Bearer ${token}` : undefined,
      },
    }
  );
};

// 提交用户反馈
export const submitFeedback = (
  assetId: number,
  data: {
    feedback_type: "correct" | "partial" | "wrong";
    suggested_department?: string;
    feedback_comment?: string;
  }
) => {
  const token = getToken175();
  return http.request<Result>(
    "post",
    `/api/suspected-assets/${assetId}/feedback`,
    {
      data,
      headers: {
        Authorization: token ? `Bearer ${token}` : undefined,
      },
    }
  );
};

// 修改部门归属
export const updateDepartment = (
  assetId: number,
  data: {
    new_department: string;
    change_reason: string;
  }
) => {
  const token = getToken175();
  return http.request<Result>(
    "post",
    `/api/suspected-assets/${assetId}/update-department`,
    {
      data,
      headers: {
        Authorization: token ? `Bearer ${token}` : undefined,
      },
    }
  );
};

// AI训练相关接口
// 获取训练统计
export const getTrainingStats = () => {
  const token = getToken175();
  return http.request<Result>("get", "/api/ai-training/stats", {
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 获取推荐部门
export const getRecommendedDepartments = (data: {
  ip?: string;
  port?: number;
  title?: string;
}) => {
  const token = getToken175();
  return http.request<Result>("post", "/api/ai-training/recommend", {
    data,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 提交训练样本
export const submitTrainingLabel = (data: {
  department_label: string;
  sample_type: "positive" | "negative";
  ip?: string;
  port?: number;
  confidence?: number;
  title?: string;
  service_type?: string;
  middleware_info?: string;
  domain_name?: string;
  keywords?: string;
  banner_info?: string;
  note?: string;
}) => {
  const token = getToken175();
  return http.request<Result>("post", "/api/ai-training/label", {
    data,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 资产画像图谱相关接口
// 获取资产画像图谱
export const getAssetProfileGraph = (params: {
  asset_id: number;
  with_debug?: boolean;
}) => {
  const token = getToken175();
  return http.request<Result>("get", "/api/asset-profile/graph", {
    params,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 告警相关接口
// 批量创建告警
export const batchCreateAlerts = (data: { suspected_asset_ids: number[] }) => {
  const token = getToken175();
  return http.request<Result>(
    "post",
    "/api/suspected-assets/batch-create-alerts",
    {
      data,
      headers: {
        Authorization: token ? `Bearer ${token}` : undefined,
      },
    }
  );
};

// 批量查询告警状态
export const batchQueryAlertStatus = (data: {
  suspected_asset_ids: number[];
}) => {
  const token = getToken175();
  return http.request<Result>("post", "/api/suspected-assets/alert-status", {
    data,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 查询单个资产的告警详情
export const getAssetAlert = (assetId: number) => {
  const token = getToken175();
  return http.request<Result>("get", `/api/suspected-assets/${assetId}/alert`, {
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 统计报表相关接口
// 获取综合统计接口
export const getReportOverview = (params?: {
  time_range?: "7d" | "30d" | "90d" | "1y" | "custom" | string;
  compare_with?: "last_week" | "last_month" | "last_year";
  include_trends?: boolean;
  department_id?: number;
  metrics?: "all" | "assets" | "risks" | "tasks" | "efficiency";
  start_date?: string; // 自定义时间范围开始日期
  end_date?: string; // 自定义时间范围结束日期
}) => {
  const token = getToken175();
  return http.request<Result>("get", "/api/pan/reports/overview", {
    params,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 获取趋势数据接口
export const getTrendData = (params?: {
  metric?: "asset_count" | "risk_level" | "processing_rate" | "task_execution";
  time_range?: "7d" | "30d" | "90d" | "1y" | "custom" | string;
  granularity?: "hourly" | "daily" | "weekly" | "monthly";
  department_id?: number;
  group_by?: "none" | "risk_level" | "department" | "status";
  compare_periods?: number;
  start_date?: string; // 自定义时间范围开始日期
  end_date?: string; // 自定义时间范围结束日期
}) => {
  const token = getToken175();
  return http.request<Result>("get", "/api/pan/reports/trends", {
    params,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 获取分布统计接口
export const getDistributionData = (params?: {
  dimension?:
    | "risk_level"
    | "department"
    | "scene_type"
    | "file_type"
    | "processing_time";
  time_range?: "7d" | "30d" | "90d" | "1y" | "custom" | string;
  include_details?: boolean;
  department_id?: number;
  threshold_type?: "absolute" | "percentage";
  start_date?: string; // 自定义时间范围开始日期
  end_date?: string; // 自定义时间范围结束日期
}) => {
  const token = getToken175();
  return http.request<Result>("get", "/api/pan/reports/distribution", {
    params,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 获取对比分析接口
export const getComparisonData = (params?: {
  comparison_type?: "department" | "time_period" | "risk_level" | "scene_type";
  items?: string; // 对比项目ID，逗号分隔
  time_range?: "7d" | "30d" | "90d" | "1y" | "custom" | string;
  metrics?: "all" | "asset_count" | "processing_rate" | "risk_score" | string;
  baseline?: "average" | "best" | "worst" | "custom";
  baseline_value?: number; // 自定义基准值
  start_date?: string; // 自定义时间范围开始日期
  end_date?: string; // 自定义时间范围结束日期
}) => {
  const token = getToken175();
  return http.request<Result>("get", "/api/pan/reports/comparison", {
    params,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 获取详细报表接口
export const getDetailReport = (params?: {
  report_type?: "department" | "asset" | "task" | "risk" | "responsible_person";
  time_range?: "7d" | "30d" | "90d" | "1y" | "custom" | string;
  group_by?: string; // 分组方式
  sort_by?: string; // 排序字段
  sort_order?: "asc" | "desc"; // 排序方向
  page?: number; // 页码
  per_page?: number; // 每页数量
  start_date?: string; // 自定义时间范围开始日期
  end_date?: string; // 自定义时间范围结束日期
}) => {
  const token = getToken175();
  return http.request<Result>("get", "/api/pan/reports/detail", {
    params,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 导出报表接口
export const exportReport = (data: {
  report_type: string; // 报表类型 (必填)
  format?: "xlsx" | "csv" | "pdf"; // 导出格式
  time_range?: "7d" | "30d" | "90d" | "1y" | "custom" | string; // 时间范围
  include_charts?: boolean; // 是否包含图表
  include_trends?: boolean; // 是否包含趋势数据
  include_comparison?: boolean; // 是否包含对比数据
  department_ids?: number[]; // 指定部门ID
  language?: string; // 报表语言
  template?: "standard" | "detailed" | "summary"; // 报表模板
  custom_fields?: string[]; // 自定义字段
  exported_by?: string; // 导出者
  start_date?: string; // 自定义时间范围开始日期
  end_date?: string; // 自定义时间范围结束日期
}) => {
  const token = getToken175();
  return http.request<Result>("post", "/api/pan/reports/export", {
    data,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 获取报表模板接口
export const getReportTemplates = (params?: {
  report_type?: "department" | "asset" | "task" | "risk" | "responsible_person";
  template_category?: "performance" | "summary" | "detailed";
  language?: string; // 语言
}) => {
  const token = getToken175();
  return http.request<Result>("get", "/api/pan/reports/templates", {
    params,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 获取性能指标接口
export const getPerformanceMetrics = (params?: {
  time_range?: "7d" | "30d" | "90d" | "1y" | "custom" | string; // 时间范围
  department_id?: number; // 部门筛选
  metric_category?: "all" | "efficiency" | "quality" | "responsiveness"; // 指标分类
  include_benchmarks?: boolean; // 是否包含基准值
  calculation_method?: "average" | "weighted" | "median"; // 计算方法
  start_date?: string; // 自定义时间范围开始日期
  end_date?: string; // 自定义时间范围结束日期
}) => {
  const token = getToken175();
  return http.request<Result>("get", "/api/pan/reports/performance-metrics", {
    params,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// ==================== 网盘快速查询相关接口 ====================

// 快速搜索接口
export const quickSearch = (data?: {
  keyword: string; // 必填：搜索关键词
  page?: number; // 可选：页码，默认1
  category?: number; // 可选：文件分类 0=全部,1=视频,2=音乐,3=图片,4=文档,5=软件,6=压缩包,7=BT种子
  diffDay?: number; // 可选：时间范围 7/30/90/365天
  searchType?: "match" | "precise"; // 可选：搜索类型 match=模糊搜索,precise=精确搜索
  resType?: "baidu" | "quark" | "xunleipan"; // 可选：网盘类型
  minSize?: number; // 可选：最小文件大小(字节)
  maxSize?: number; // 可选：最大文件大小(字节)
}) => {
  return taskRequest<Result>("post", "/api/pan/quick-search/", data);
};

// 获取资源详情接口
export const getResourceDetail = (data?: {
  resource_id: string; // 必填：资源ID
  resource_type: "baidu" | "quark" | "xunleipan"; // 必填：资源类型
  keyword: string; // 必填：搜索关键词
}) => {
  const token = getToken175();
  return http.request<Result>("post", "/api/pan/quick-search/detail", {
    data,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 单个确认入库接口
export const confirmResource = (data?: {
  search_id: string;
  original_data: {
    id: string;
    filename: string;
    size: number;
    ext?: string;
    user?: string;
    updatetime?: string;
    url?: string;
  };
  keyword: string;
  risk_score?: number;
  risk_level?: "high" | "medium" | "low";
  responsible_department?: string;
  responsible_person?: string;
  confirm_reason?: string;
}) => {
  const token = getToken175();
  return http.request<Result>("post", "/api/pan/quick-search/confirm", {
    data,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 批量确认入库接口
export const batchConfirmResources = (data?: {
  results: Array<{
    search_id: string;
    original_data: {
      id: string;
      filename: string;
      size: number;
      ext?: string;
      user?: string;
      updatetime?: string;
      url?: string;
    };
    keyword: string;
    risk_score?: number;
    risk_level?: "high" | "medium" | "low";
  }>;
  responsible_department?: string;
  responsible_person?: string;
  confirm_reason?: string;
}) => {
  const token = getToken175();
  return http.request<Result>("post", "/api/pan/quick-search/batch-confirm", {
    data,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// ==================== 网盘资产管理相关接口 ====================

// 获取资产列表接口
export const getPanAssets = (params?: {
  page?: number; // 页码，默认1
  per_page?: number; // 每页数量，默认20，最大100
  keyword?: string; // 文件名关键词搜索
  risk_level?: "critical" | "high" | "medium" | "low"; // 风险等级筛选
  status?: "pending" | "confirmed" | "ignored"; // 状态筛选
  scene_type?: string; // 场景类型筛选
  department?: string; // 责任部门筛选
  start_date?: string; // 开始日期
  end_date?: string; // 结束日期
  sort_by?: string; // 排序字段
  sort_order?: "asc" | "desc"; // 排序方向
}) => {
  const token = getToken175();
  return http.request<Result>("get", "/api/pan/assets", {
    params,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 获取资产详情接口
export const getPanAssetDetail = (assetId: number) => {
  const token = getToken175();
  return http.request<Result>("get", `/api/pan/assets/${assetId}`, {
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 更新资产接口
export const updatePanAsset = (
  assetId: number,
  data?: {
    filename?: string;
    risk_score?: number;
    risk_level?: "critical" | "high" | "medium" | "low";
    confirmed_department?: string;
    confirmed_person?: string;
    review_status?: "pending" | "confirmed" | "ignored";
    review_comment?: string;
    verification_status?: "verified" | "unverified" | "verifying";
  }
) => {
  const token = getToken175();
  return http.request<Result>("put", `/api/pan/assets/${assetId}`, {
    data,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 批量确认资产接口
export const batchConfirmPanAssets = (data?: {
  asset_ids: number[]; // 资产ID列表 (必填)
  confirmed_department?: string; // 责任部门 (可选)
  confirmed_person?: string; // 责任人 (可选)
  confirm_reason?: string; // 确认原因 (可选)
}) => {
  const token = getToken175();
  return http.request<Result>("post", "/api/pan/assets/batch-confirm", {
    data,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 批量忽略资产接口
export const batchIgnorePanAssets = (data?: {
  asset_ids: number[]; // 资产ID列表 (必填)
  ignored_reason?: string; // 忽略原因 (可选)
}) => {
  const token = getToken175();
  return http.request<Result>("post", "/api/pan/assets/batch-ignore", {
    data,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 批量删除资产接口
export const batchDeletePanAssets = (data?: {
  asset_ids: number[]; // 资产ID列表 (必填)
  delete_reason?: string; // 删除原因 (可选)
}) => {
  const token = getToken175();
  return http.request<Result>("post", "/api/pan/assets/batch-delete", {
    data,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 资产统计接口
export const getPanAssetsStatistics = (data?: {
  time_range?: "7d" | "30d" | "90d" | "1y"; // 时间范围
  group_by?: "risk_level" | "status" | "department" | "scene_type"; // 分组方式
  department?: string; // 部门筛选
  scene_type?: string; // 场景类型筛选
}) => {
  const token = getToken175();
  return http.request<Result>("post", "/api/pan/assets/statistics", {
    data,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 导出资产接口
export const exportPanAssets = (params?: {
  format?: "xlsx" | "csv"; // 导出格式
  asset_ids?: string; // 指定资产ID，逗号分隔
  keyword?: string; // 关键词筛选
  risk_level?: "critical" | "high" | "medium" | "low"; // 风险等级筛选
  status?: "pending" | "confirmed" | "ignored"; // 状态筛选
  department?: string; // 部门筛选
  start_date?: string; // 开始日期
  end_date?: string; // 结束日期
}) => {
  const token = getToken175();
  return http.request<Blob>("get", "/api/pan/assets/export", {
    params,
    responseType: "blob",
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// ==================== 网盘任务管理相关接口 ====================

// 获取任务列表接口
export const getPanTasks = (data?: {
  page?: number; // 页码，默认1
  per_page?: number; // 每页数量，默认20，最大100
  task_name?: string; // 任务名称搜索 (可选)
  task_status?: "running" | "pending" | "paused" | "completed" | "failed"; // 任务状态筛选 (可选)
  task_type?: "standard" | "custom" | "system"; // 任务类型筛选 (可选)
  scenario_type?: string; // 场景类型筛选 (可选)
  created_by?: string; // 创建者筛选 (可选)
  start_date?: string; // 创建时间起始 (可选)
  end_date?: string; // 创建时间结束 (可选)
  schedule_enabled?: boolean; // 是否启用调度 (可选)
  sort_by?: string; // 排序字段 (可选)
  sort_order?: "asc" | "desc"; // 排序方向 (可选)
  main_keyword?: string; // 主关键词搜索 (可选)
}) => {
  const token = getToken175();
  return http.request<Result>("post", "/api/pan/tasks", {
    data,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 更新任务状态接口
export const updateTaskStatus = (
  taskCode: string | string[],
  status: "pause" | "resume"
) => {
  const token = getToken175();
  const taskCodes = Array.isArray(taskCode) ? taskCode : [taskCode];
  return http.request<Result>("post", "/api/pan/tasks/batch-update-status", {
    data: {
      task_codes: taskCodes,
      status,
    },
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 删除任务接口
export const deleteTask = (taskCode: string) => {
  const token = getToken175();
  return http.request<Result>("delete", `/api/pan/tasks/${taskCode}`, {
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 导出任务接口
export const exportTasks = (data?: {
  task_codes?: string[]; // 任务编码列表 (可选)
  format?: "xlsx" | "csv"; // 导出格式 (可选，默认xlsx)
}) => {
  const token = getToken175();
  return http.request<Blob>("post", "/api/pan/tasks/export", {
    data,
    responseType: "blob",
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// ==================== 网盘场景配置相关接口 ====================

// 获取场景列表接口
export const getPanScenes = (params?: {
  page?: number; // 页码，默认1
  per_page?: number; // 每页数量，默认20，最大100
  scene_name?: string; // 场景名称搜索 (支持模糊匹配)
  is_enabled?: boolean; // 是否启用筛选 (true/false)
  is_custom?: boolean; // 是否自定义筛选 (true/false)
  category?: string; // 分类筛选
  priority_level?: "low" | "medium" | "high"; // 优先级筛选
  created_by?: string; // 创建者筛选
  sort_by?: "scene_name" | "created_time" | "usage_count" | "is_enabled"; // 排序字段
  sort_order?: "asc" | "desc"; // 排序方向
}) => {
  const token = getToken175();
  return http.request<Result>("get", "/api/pan/scene-management/scenes", {
    params,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 获取场景详情接口
export const getPanSceneDetail = (sceneId: number) => {
  const token = getToken175();
  return http.request<Result>(
    "get",
    `/api/pan/scene-management/scenes/${sceneId}`,
    {
      headers: {
        Authorization: token ? `Bearer ${token}` : undefined,
      },
    }
  );
};

// 删除场景接口
export const deletePanScene = (sceneId: number, force?: boolean) => {
  const token = getToken175();
  return taskRequest<Result>(
    "delete",
    `/api/pan/scene-management/scenes/${sceneId}`,
    {
      params: { force },
    }
  );
};

// 启用/禁用场景接口
export const togglePanScene = (
  sceneId: number,
  data: {
    is_enabled: boolean;
    updated_by?: string;
  }
) => {
  return taskRequest<Result>(
    "put",
    `/api/pan/scene-management/scenes/${sceneId}/toggle`,
    data
  );
};

// 创建场景接口
export const createPanScene = (data: {
  scene_name: string; // 必填, 最长50字符
  main_keywords: string[]; // 必填, 数组至少1个
  description?: string; // 可选, 最长200字符
  aux_keywords?: string[]; // 可选, 数组
  category?: string; // 可选
  tags?: string[]; // 可选, 数组
  priority_level?: "low" | "medium" | "high"; // 可选
  responsible_department?: string; // 可选
  default_action?: "review" | "alert" | "ticket"; // 可选
  config?: {
    auto_cleanup?: boolean;
    retention_days?: number;
    cache_enabled?: boolean;
    max_results?: number;
    search_timeout?: number;
  }; // 可选, JSON对象
  created_by?: string; // 可选
}) => {
  return taskRequest<Result>("post", "/api/pan/scene-management/scenes", {
    data,
  });
};

// 更新场景接口
export const updatePanScene = (
  sceneId: number,
  data: {
    scene_name?: string; // 可选
    description?: string; // 可选
    main_keywords?: string[]; // 可选
    aux_keywords?: string[]; // 可选
    is_enabled?: boolean; // 可选
    category?: string; // 可选
    tags?: string[]; // 可选
    priority_level?: "low" | "medium" | "high"; // 可选
    responsible_department?: string; // 可选
    default_action?: "review" | "alert" | "ticket"; // 可选
    config?: {
      auto_cleanup?: boolean;
      retention_days?: number;
      cache_enabled?: boolean;
      max_results?: number;
      search_timeout?: number;
    }; // 可选
    updated_by?: string; // 可选
  }
) => {
  return taskRequest<Result>(
    "put",
    `/api/pan/scene-management/scenes/${sceneId}`,
    {
      data,
    }
  );
};

// 获取关键词库接口
export const getSceneKeywords = (params?: {
  category?: string; // 关键词分类 (可选)
  keyword?: string; // 关键词搜索 (可选)
  page?: number; // 页码，默认1
  per_page?: number; // 每页数量，默认50
}) => {
  return taskRequest<Result>("get", "/api/pan/scenes/keywords", {
    params,
  });
};

// ==================== 缓存管理相关接口 ====================

// 获取缓存统计接口
export const getCacheStatistics = (params?: {
  time_range?: "1h" | "24h" | "7d" | "30d"; // 时间范围 (可选)
  include_details?: boolean; // 是否包含详细信息 (可选)
}) => {
  const token = getToken175();
  return http.request<Result>("get", "/api/pan/cache/statistics", {
    params,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 获取低分资产列表接口
export const getCacheAssets = (params?: {
  page?: number; // 页码 (必填)
  per_page?: number; // 每页数量 (必填)
  task_id?: number; // 任务ID (可选)
  min_risk_score?: number; // 最低风险评分 (可选)
  max_risk_score?: number; // 最高风险评分 (可选)
  keyword?: string; // 关键词筛选 (可选)
  sort_by?: "cached_at" | "risk_score"; // 排序字段 (可选)
  sort_order?: "asc" | "desc"; // 排序方向 (可选)
}) => {
  const token = getToken175();
  return http.request<Result>("get", "/api/pan/cache/assets", {
    params,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 获取资产详情接口
export const getCacheAssetDetail = (tempId: string) => {
  const token = getToken175();
  return http.request<Result>("get", `/api/pan/cache/assets/${tempId}`, {
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 批量确认资产接口
export const batchConfirmCacheAssets = (data: {
  temp_ids: string[]; // 临时ID数组 (必填)
  responsible_department?: string; // 责任部门 (可选)
  responsible_person?: string; // 责任人 (可选)
  confirm_reason?: string; // 确认原因 (可选)
}) => {
  const token = getToken175();
  return http.request<Result>("post", "/api/pan/cache/assets/batch-confirm", {
    data,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 批量忽略资产接口
export const batchIgnoreCacheAssets = (data: {
  temp_ids: string[]; // 临时ID数组 (必填)
  ignore_reason?: string; // 忽略原因 (可选)
}) => {
  const token = getToken175();
  return http.request<Result>("post", "/api/pan/cache/assets/batch-ignore", {
    data,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 删除单个资产接口
export const deleteCacheAsset = (tempId: string) => {
  const token = getToken175();
  return http.request<Result>("delete", `/api/pan/cache/assets/${tempId}`, {
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 批量删除资产接口
export const batchDeleteCacheAssets = (data: {
  temp_ids: string[]; // 临时ID数组 (必填)
}) => {
  const token = getToken175();
  return http.request<Result>("post", "/api/pan/cache/assets/batch-delete", {
    data,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// ==================== 部门管理相关接口 ====================

// 获取部门列表接口
export const getPanDepartments = (params?: {
  page?: number; // 页码，默认1
  per_page?: number; // 每页数量，默认20，最大100
  department_name?: string; // 部门名称模糊搜索 (可选)
  status?: "active" | "inactive" | "archived"; // 状态筛选 (可选)
  responsible_person?: string; // 责任人姓名搜索 (可选)
  sort_by?:
    | "department_name"
    | "total_assets"
    | "processing_rate"
    | "created_time"; // 排序字段 (可选)
  sort_order?: "asc" | "desc"; // 排序方向 (可选)
}) => {
  const token = getToken175();
  return http.request<Result>("get", "/api/pan/departments", {
    params,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 获取部门详情接口
export const getPanDepartmentDetail = (departmentId: number) => {
  const token = getToken175();
  return http.request<Result>("get", `/api/pan/departments/${departmentId}`, {
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 创建部门接口
export const createPanDepartment = (data: {
  department_name: string; // 部门名称 (必填，唯一)
  department_code?: string; // 部门代码 (可选，唯一，不填自动生成)
  description?: string; // 部门描述 (可选)
  responsible_person?: string; // 责任人姓名 (可选)
  responsible_email?: string; // 责任人邮箱 (可选)
  responsible_phone?: string; // 责任人电话 (可选)
  responsible_title?: string; // 责任人职务 (可选)
  backup_person?: string; // 备用责任人姓名 (可选)
  backup_email?: string; // 备用责任人邮箱 (可选)
  backup_phone?: string; // 备用责任人电话 (可选)
  status?: "active" | "inactive" | "archived"; // 状态 (可选, 默认active)
  config?: any; // 配置JSON (可选)
  created_by?: string; // 创建者 (可选)
}) => {
  const token = getToken175();
  return http.request<Result>("post", "/api/pan/departments", {
    data,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 更新部门接口
export const updatePanDepartment = (
  departmentId: number,
  data: {
    department_name?: string; // 部门名称 (可选)
    department_code?: string; // 部门代码 (可选)
    description?: string; // 部门描述 (可选)
    responsible_person?: string; // 责任人姓名 (可选)
    responsible_email?: string; // 责任人邮箱 (可选)
    responsible_phone?: string; // 责任人电话 (可选)
    responsible_title?: string; // 责任人职务 (可选)
    backup_person?: string; // 备用责任人 (可选)
    backup_email?: string; // 备用责任人邮箱 (可选)
    backup_phone?: string; // 备用责任人电话 (可选)
    status?: "active" | "inactive" | "archived"; // 状态 (可选)
    config?: any; // 配置JSON (可选)
    updated_by?: string; // 更新者 (可选)
  }
) => {
  const token = getToken175();
  return http.request<Result>("put", `/api/pan/departments/${departmentId}`, {
    data,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 删除部门接口
export const deletePanDepartment = (departmentId: number) => {
  const token = getToken175();
  return http.request<Result>(
    "delete",
    `/api/pan/departments/${departmentId}`,
    {
      headers: {
        Authorization: token ? `Bearer ${token}` : undefined,
      },
    }
  );
};

// 获取部门综合统计接口
export const getPanDepartmentStatistics = (params?: {
  time_range?: "7d" | "30d" | "90d" | "all"; // 时间范围 (可选，默认all)
  department_id?: number; // 部门ID筛选 (可选)
}) => {
  const token = getToken175();
  return http.request<Result>("get", "/api/pan/departments/statistics", {
    params,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 查询责任人接口
export const getPanResponsiblePersons = (params?: {
  department_id?: number; // 按部门ID筛选 (可选)
  person_name?: string; // 按责任人姓名筛选 (可选)
  group_by?: "department" | "person"; // 分组方式 (可选)
  status?: "active" | "inactive" | "archived"; // 状态筛选 (可选)
  has_backup?: boolean; // 是否有备用责任人 (可选)
}) => {
  const token = getToken175();
  return http.request<Result>(
    "get",
    "/api/pan/departments/responsible-persons",
    {
      params,
      headers: {
        Authorization: token ? `Bearer ${token}` : undefined,
      },
    }
  );
};

// 批量分配资产接口
export const batchAssignAssetsToDepartments = (data: {
  assignments: Array<{
    asset_id: number; // 资产ID (必填)
    department_name: string; // 部门名称 (必填)
    assignment_type: "ai_inference" | "manual_confirm"; // 分配类型 (必填)
  }>;
  assigned_by?: string; // 分配者 (可选)
}) => {
  const token = getToken175();
  return http.request<Result>(
    "post",
    "/api/pan/departments/batch-assign-enhanced",
    {
      data,
      headers: {
        Authorization: token ? `Bearer ${token}` : undefined,
      },
    }
  );
};
